package com.itbaizhan;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**分页测试类*/
public class PageTest01 {
    //分页查询users表
    //泛型用Users，因为是查询返回的对象
    //Page的作用：将分页查询的方法的参数通过Page传过来
    //Page的作用:把查询的数据结果集封装起来，再传递给视图
    public Page01<Users> selectPage(Page01 page01){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Users> list = new ArrayList<>();
        try{
            conn = JdbcUtils.getConnection();
            ps = conn.prepareStatement("select * from users limit ?,?");
            //绑定m参数，m=（当前页-1）*每页显示的条数
            ps.setInt(1,(page01.getCurrentPage() - 1)*page01.getPageSize());
            //绑定n参数，n是显示每页的条数
            ps.setInt(2,page01.getPageSize());
            //执行查询
            rs =ps.executeQuery();
            //处理结果集
            while (rs.next()){
                //完成ORM映射
                Users users = new Users();
                users.setUserid(rs.getInt("userid"));
                users.setUsername(rs.getString("username"));
                users.setUsergae(rs.getInt("userage"));
                list.add(users);
            }
            //将结果集放入Page
            page01.setResult(list);
            //查询总条数
            ps = conn.prepareStatement("select count(*) from users");
            //执行语句
            rs = ps.executeQuery();
            while (rs.next()){
                //取结果 可以给列名，也可以给序号，第几列
                int count = rs.getInt(1);
                //保存总条数
                page01.setTotalCount(count);
                //换算总页数 = 总条数/每页显示的条数 向上取整（条数不中一页）
                //Math.ceil()这方法返回的是double类型，所以*1.0
                int totalPage = (int)Math.ceil(1.0*count/ page01.getPageSize());
                //保存
                page01.setTotalPage(totalPage);

            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JdbcUtils.closeResource(rs,ps,conn);
        }
       return page01;
    }

    public static void main(String[] args) {
        PageTest01 pt = new PageTest01();
        Page01 pg = new Page01();
        pg.setCurrentPage(1);
        pg.setPageSize(2);
        Page01 page1 = pt.selectPage(pg);
        System.out.println("总条数 "+page1.getTotalCount());
        System.out.println("总页数 "+page1.getTotalPage());
        System.out.println("当前页 "+page1.getCurrentPage());
        System.out.println("每页显示的条数 "+page1.getPageSize());
        List<Users> list = page1.getResult();
        for(Users user:list){
            System.out.println(user.getUserid()+" "+user.getUsername()+" "+ user.getUsergae());
        }
    }

}
